/**
 * Created by xiaomin on 2015/6/19.
 */

var defDirective = angular.module('defDirective', []);


function dialog(attr, callback) {
    // 初始化弹出框
    var dialog = $("#dialog-" + attr.renderDialog + "").removeClass('hide').dialog({
        modal: true,
        title: "<div class='widget-header widget-header-small'><h4 class='smaller'>" + attr.title + "</h4></div>",
        title_html: true,
        width: 600,
        buttons: [
            {
                text: "取消",
                "class": "btn btn-xs",
                click: function () {
                    $(".select_pointer").unbind("click");
                    $(this).dialog("close");
                }
            },
            {
                text: "确定",
                "class": "btn btn-primary btn-xs save",
                click: function () {
                    callback();
                    $(".select_pointer").unbind("click");
                    $(this).dialog("close");
                }
            }
        ]
    });
}


/**
 * ng-repeat遍历完成后再初始化表格
 */
defDirective.directive('onFinishRenderFilters', ['$rootScope', '$timeout', function ($rootScope, $timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr, controller) {          // 每个使用该指令的元素都会执行一次这个函数

            // $index $last $first $middle even odd 均为ng-repeat生成的实例作用于中的一些特殊属性,console.log(scope);即可看到。
            if (scope.$last === true) {
                //下面是在table render完成后执行的js
                var len = $("th").length, arry = [];

                for (var i = 0; i < len; i++) {
                    if (i == 0) {
                        arry[i] = {"bSortable": false};
                    }
                    else {
                        arry[i] = null;
                    }
                }

                //  初始化表格
                var table =
                    $('#sample-table-1')
                        .dataTable({
                            retrieve: true,
                            bAutoWidth: false,
                            "aoColumns": arry,
                            "aaSorting": []
                        });

                $(document).on('click', 'th input:checkbox', function () {
                    var that = this;
                    $(this).closest('table').find('tr > td:first-child input:checkbox')
                        .each(function () {
                            this.checked = that.checked;
                            $(this).closest('tr').toggleClass('selected');
                        });
                });

                // 统一删除
                $(".delete").bind('click', function () {
                    var count = 0, ifDel = [];
                    $("table tr>td:first-child input:checkbox").each(function () {
                        if ($(this).is(':checked')) {  // $(this).prop("checked") 属性值为true或false时用prop（）代替attr（）
                            count++;
                            ifDel.push($(this).closest("tr").data("id"));
                        }
                    })

                    if (count > 1) {
                        if (confirm("是否删除选中的 " + count + " 条数据？")) {
                            scope.$emit("delBatch", ifDel);
                        }
                    } else if (count == 1) {
                        if (confirm("是否确定删除？")) {
                            scope.$emit("delSingle", ifDel);
                        }
                    } else {
                        alert("请选择要删除的数据");
                    }
                });

                // 角色授权
                $(".privilege").bind('click', function () {
                    var thiz = $(this),
                        rid = thiz.data("id"),
                        data = {
                            renderDialog: thiz.data("dialog"),
                            title: thiz.attr("title")
                        };

                    dialog(data, function () {
                        var ids = [];
                        $(".select_content").find("li").each(function () {
                            if ($(this).hasClass("leaf_selected")) {
                                ids.push($(this).data("id"));
                            }
                        });
                        console.log(ids);
                        scope.$emit("authorization", {rid: rid, pids: ids});
                    });
                    scope.$emit("unique", rid);

                });

                // 统一更新
                $(".update").bind('click', function () {
                    var thiz = $(this);
                    scope.$emit("getRolesList");
                    scope.$emit("unique", $(this).data("id"));

                    var data = {
                        renderDialog: thiz.data("dialog"),
                        title: thiz.attr("title")
                    };

                    dialog(data, function () {
                        var ids = [];
                        $(".select_content").find("li").each(function () {
                            if ($(this).hasClass("leaf_selected")) {
                                ids.push($(this).data("id"));
                            }
                        });
                        console.log(ids);
                        scope.$emit("update", ids);
                    });

                    $(".select_pointer").bind('click', function () {
                        $(".select_content").slideToggle();
                    });
                });

            }
        }
    };
}]);

/**
 *  适用于所有弹出框，给弹出框添加事件等
 */
defDirective.directive('renderDialog', function ($timeout) {
    return {
        restrict: 'A',
        controller: function ($scope) {
            $scope.initDialog = function (attr, callback) {
                // 初始化弹出框
                dialog(attr, function () {
                    callback();
                });
            }
        },
        link: function (scope, element, attr) {              // 利用attr获取元素的属性，指令的值仍然采用驼峰式

            // 给元素绑定点击事件
            element.on('click', function (e) {
                e.preventDefault();
                scope.user = {};

                $("#dialog-" + attr.renderDialog + "").find("input").val();
                scope.$emit("getRolesList");

                // 初始化弹出框
                scope.initDialog(attr, function () {
                    var ids = [];
                    $(".select_tree .select_content").find("li").each(function () {
                        if ($(this).hasClass("leaf_selected")) {
                            ids.push($(this).data("id"));
                        }
                    });
                    console.log(ids);
                    scope.$emit("save", ids);   // “订阅者模式”
                });

                $(".select_pointer").bind('click', function () {
                    $(".select_content").slideToggle();
                });

            });

        }
    }
});


defDirective.directive('onTreeSelect', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {

            if (scope.$last === true) {

                $timeout(function () {
                    // 必须要用$timeout，不能用$(document).ready(function(){})，否则获取到的是 {{*}}，$timeout 的意思是在浏览器渲染之后才执行。
                    //   $(document).ready(function(){})在DOM结构绘制完毕后执行，不必等到加载完毕。
                    // scope.$scope("$viewContentLoaded",function(){
                    $("#example-advanced").treetable({
                        expandable: true,
                        column: 1,  // column与columnElType 表示字体图标显示在下标为1的td内，column默认值是0
                        columnElType: "td",
                        outerEle: "table",  // 外层父元素
                        innerEle: "tr",         // 内层行数
                        commonClass: "glyphicon",
                        expandClass: "glyphicon-plus",  // 收缩时的CSS样式
                        indenterClass: "glyphicon-minus"    // 展开时的CSS样式
                    });
                    //});


                    $("#myTreeSelector").treetable({
                        expandable: true,
                        columnElType: "div",
                        outerEle: "ul",
                        innerEle: "li",
                        commonClass: "glyphicon",
                        expandClass: "glyphicon-plus",
                        indenterClass: "glyphicon-minus"
                    });
                }, 0, false);

                var  $dumpl_select =  element.parent();
                $dumpl_select.find("li").each(function () {
                    var thiz = $(this);
                    thiz.on('click', function () {
                        thiz.toggleClass("leaf_selected");
                        var ppId = thiz.data("ttParentId");
                        if (thiz.hasClass("leaf_selected") && ppId) {

                            $dumpl_select.find("li[data-tt-id=" + ppId + "]").addClass("leaf_selected")
                                .bind('click', function () {
                                    $dumpl_select.find("li[data-tt-parent-id=" + ppId + "]").removeClass("leaf_selected");
                                })
                        }
                    });
                });

                var toggle = function () {
                    if (this.hasClass("leaf_selected")) {
                        this.removeClass("leaf_selected");
                    } else {
                        this.addClass("leaf_selected").siblings().removeClass("leaf_selected");
                        $(".select_pointer .select_font").html(this.find("span.ng-binding").html());
                    }
                }
                $(".single_select").find("li").each(function () {
                    var thiz = $(this);
                    thiz.on('click', function () {
                        toggle.apply(thiz, arguments);
                    });
                });


            }
        }
    }
}]);

defDirective.directive('onTreeTalbe', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {

            if (scope.$last === true) {

                $timeout(function () {
                    $("#example-advanced").treetable({
                        expandable: true,
                        column: 1,  // column与columnElType 表示字体图标显示在下标为1的td内，column默认值是0
                        columnElType: "td",
                        outerEle: "table",  // 外层父元素
                        innerEle: "tr",         // 内层行数
                        commonClass: "glyphicon",
                        expandClass: "glyphicon-plus",  // 收缩时的CSS样式
                        indenterClass: "glyphicon-minus"    // 展开时的CSS样式
                    });
                }, 0, false);
            }
        }
    }
}]);
/**
 * 删除指令
 */
defDirective.directive('delete', function () {

});

defDirective.directive("edit", ['$document', '$timeout', function ($document, $timeout) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind("click", function () {
                scope.$emit("unique",ngModel.$modelValue.id);
                //scope.$emit("show", ngModel.$modelValue);

            });
        }
    }
}]);

defDirective.directive("update", function ($document) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind("click", function () {
                var ids = [];
                $(".select_content").find("li").each(function () {
                    if ($(this).hasClass("leaf_selected")) {
                        ids.push($(this).data("id"));
                    }
                });
            console.log(ngModel.$modelValue);
                scope.$emit("update", {obj:ngModel.$modelValue,ids:ids});
            })
        }
    }
});

